const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
require('dotenv').config();

// 生成 JWT 令牌
const generateToken = (user) => {
  return jwt.sign(
    {
      id: user.id,
      username: user.username,
      isAdmin: user.isAdmin || false
    },
    process.env.JWT_SECRET || 'your_jwt_secret',
    {
      expiresIn: '24h'
    }
  );
};

// 验证密码
const validatePassword = async (password, hashedPassword) => {
  return await bcrypt.compare(password, hashedPassword);
};

// 生成唯一ID
const generateUniqueId = () => {
  return Math.random().toString(36).substring(2, 11);
};

// 格式化日期
const formatDate = (date) => {
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const hours = String(d.getHours()).padStart(2, '0');
  const minutes = String(d.getMinutes()).padStart(2, '0');
  const seconds = String(d.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 验证会员状态
const checkMembershipValid = (expiryDate) => {
  if (!expiryDate) return false;
  const expiry = new Date(expiryDate);
  const now = new Date();
  return expiry > now;
};

// 获取会员等级名称
const getMembershipLevelName = (level, expiryDate) => {
  if (!checkMembershipValid(expiryDate)) return '普通用户';
  switch(level) {
    case 1: return '黄金会员';
    case 2: return '铂金会员';
    case 3: return '钻石会员';
    default: return '普通用户';
  }
};

module.exports = {
  generateToken,
  validatePassword,
  generateUniqueId,
  formatDate,
  checkMembershipValid,
  getMembershipLevelName
};